import subprocess
import sys
import os

def initialize_playwright():
    """初始化 Playwright，确保浏览器已安装"""
    try:
        from playwright.sync_api import sync_playwright
        
        # 尝试启动浏览器来验证是否已安装
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=True)
            browser.close()
        print("Playwright 浏览器已就绪")
        return True
    except Exception as e:
        print(f"Playwright 未正确配置: {e}")
        return False

def install_playwright_browsers():
    """在运行时安装 Playwright 浏览器"""
    try:
        print("正在安装 Playwright 浏览器...")
        # 使用 subprocess 调用 playwright install
        result = subprocess.run([
            sys.executable, "-m", "playwright", "install", "chromium"
        ], capture_output=True, text=True, timeout=300)
        
        if result.returncode == 0:
            print("Playwright 浏览器安装成功")
            return True
        else:
            print(f"Playwright 安装失败: {result.stderr}")
            return False
    except Exception as e:
        print(f"Playwright 安装过程中出错: {e}")
        return False

# 在创建 Flask 应用之前处理 Playwright
if getattr(sys, 'frozen', False):
    # 打包后的环境
    print("检测到打包环境，检查 Playwright 配置...")
    if not initialize_playwright():
        print("正在自动安装 Playwright 浏览器...")
        # 在打包环境中尝试设置浏览器路径
        try:
            # 设置Playwright浏览器路径
            if hasattr(sys, '_MEIPASS'):
                browser_path = os.path.join(sys._MEIPASS, 'playwright-browsers')
                if os.path.exists(browser_path):
                    os.environ['PLAYWRIGHT_BROWSERS_PATH'] = browser_path
        except Exception as e:
            print(f"设置浏览器路径失败: {e}")
        
        # 再次尝试初始化
        if not initialize_playwright():
            # 如果还是失败，尝试重新安装
            if install_playwright_browsers():
                if not initialize_playwright():
                    print("警告: Playwright 仍然无法正常工作")
            else:
                print("错误: 无法安装 Playwright 浏览器")

# 创建应用实例
from app import create_app, db
from app.models.user import User

app = create_app()

# 添加表创建逻辑
with app.app_context():
    # 创建所有未创建的表（基于模型定义）
    db.create_all()
    print("All tables created successfully")

    # 创建初始用户数据
    initial_username = 'admin'
    initial_password = '123456'
    # 检查是否已存在用户
    existing_user = User.query.filter_by(username=initial_username).first()
    if not existing_user:
        # 创建初始用户
        user = User(username=initial_username)
        user.set_password(initial_password)
        db.session.add(user)
        db.session.commit()
        print(f"Initial user '{initial_username}' created successfully")
    else:
        print(f"User '{initial_username}' already exists")

if __name__ == '__main__':
    # 启动开发服务器
    app.run(host='0.0.0.0', port=5000)